// pages/merchant/foster-room/index.js
const { FormUtils } = require('../../../utils/form-config.js');
const apiService = require('../../../utils/api.js');

Page({
  data: {
    rooms: [],
    filteredRooms: [],
    searchKeyword: '',
    showModal: false,
    showDeleteModal: false,
    isEdit: false,
    formData: {},
    isFormValid: false,
    selectedRoom: null,
    roomStats: {
      total: 0,
      available: 0,
      occupied: 0,
      maintenance: 0
    }
  },

  onLoad() {
    this.loadRooms();
  },

  onShow() {
    this.loadRooms();
  },

  // 加载房间列表
  async loadRooms() {
    try {
      wx.showLoading({ title: '加载中...' });
      
      // 模拟数据，实际应该调用API
      const mockRooms = [
        {
          _id: 'room_001',
          roomId: 1,
          roomName: '温馨单间',
          roomType: 'single',
          size: '3m x 2m',
          capacity: 1,
          price: 88,
          unit: '次',
          description: '适合小型犬，独立空间，安静舒适',
          amenities: ['恒温空调', '独立饮水', '监控摄像头'],
          careInstructions: ['每日巡视三次', '定时喂食'],
          status: 'available',
          isOccupied: false,
          currentPets: []
        },
        {
          _id: 'room_002',
          roomId: 2,
          roomName: '舒适双人间',
          roomType: 'double',
          size: '4m x 3m',
          capacity: 2,
          price: 128,
          unit: '次',
          description: '适合中型犬或两只小型犬，宽敞舒适',
          amenities: ['智能空气净化', '独立饮水', '监控摄像头'],
          careInstructions: ['每日巡视三次', '定时喂食'],
          status: 'occupied',
          isOccupied: true,
          currentPets: ['小白', '小黑']
        },
        {
          _id: 'room_003',
          roomId: 3,
          roomName: '豪华套房',
          roomType: 'suite',
          size: '5m x 4m',
          capacity: 3,
          price: 188,
          unit: '次',
          description: '适合大型犬或多只宠物，豪华配置',
          amenities: ['智能空气净化', '独立饮水', '监控摄像头', '按摩床垫', '音乐播放'],
          careInstructions: ['每日巡视四次', '定时喂食', '特殊护理'],
          status: 'maintenance',
          isOccupied: false,
          currentPets: []
        }
      ];

      // 计算统计数据
      const stats = {
        total: mockRooms.length,
        available: mockRooms.filter(r => r.status === 'available').length,
        occupied: mockRooms.filter(r => r.status === 'occupied').length,
        maintenance: mockRooms.filter(r => r.status === 'maintenance').length
      };

      this.setData({
        rooms: mockRooms,
        filteredRooms: mockRooms,
        roomStats: stats
      });

      wx.hideLoading();
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      });
      console.error('加载房间失败:', error);
    }
  },

  // 搜索输入
  onSearchInput(e) {
    const keyword = e.detail.value;
    this.setData({ searchKeyword: keyword });
    this.filterRooms(keyword);
  },

  // 过滤房间
  filterRooms(keyword) {
    const { rooms } = this.data;
    const filtered = rooms.filter(room => 
      room.roomName.toLowerCase().includes(keyword.toLowerCase()) ||
      room.roomType.toLowerCase().includes(keyword.toLowerCase())
    );
    this.setData({ filteredRooms: filtered });
  },

  // 添加房间
  onAddRoom() {
    const formData = FormUtils.initFormData('fosterRoom');
    this.setData({
      showModal: true,
      isEdit: false,
      formData,
      isFormValid: false
    });
  },

  // 编辑房间
  onEditRoom(e) {
    const item = e.currentTarget.dataset.item;
    const formData = { ...item };
    
    this.setData({
      showModal: true,
      isEdit: true,
      formData,
      selectedRoom: item,
      isFormValid: true
    });
  },

  // 切换房间状态
  async onToggleRoomStatus(e) {
    const item = e.currentTarget.dataset.item;
    const newStatus = item.status === 'available' ? 'occupied' : 'available';
    
    try {
      wx.showLoading({ title: '处理中...' });
      
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 更新本地数据
      const { rooms } = this.data;
      const updatedRooms = rooms.map(room => 
        room._id === item._id ? { ...room, status: newStatus } : room
      );
      
      // 重新计算统计数据
      const stats = {
        total: updatedRooms.length,
        available: updatedRooms.filter(r => r.status === 'available').length,
        occupied: updatedRooms.filter(r => r.status === 'occupied').length,
        maintenance: updatedRooms.filter(r => r.status === 'maintenance').length
      };
      
      this.setData({ 
        rooms: updatedRooms,
        roomStats: stats
      });
      this.filterRooms(this.data.searchKeyword);
      
      wx.hideLoading();
      wx.showToast({
        title: newStatus === 'available' ? '已设为可用' : '已设为占用',
        icon: 'success'
      });
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: '操作失败',
        icon: 'error'
      });
      console.error('切换状态失败:', error);
    }
  },

  // 删除房间
  onDeleteRoom(e) {
    const item = e.currentTarget.dataset.item;
    this.setData({
      showDeleteModal: true,
      selectedRoom: item
    });
  },

  // 确认删除
  async onConfirmDelete() {
    const { selectedRoom } = this.data;
    
    try {
      wx.showLoading({ title: '删除中...' });
      
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 更新本地数据
      const { rooms } = this.data;
      const updatedRooms = rooms.filter(room => room._id !== selectedRoom._id);
      
      // 重新计算统计数据
      const stats = {
        total: updatedRooms.length,
        available: updatedRooms.filter(r => r.status === 'available').length,
        occupied: updatedRooms.filter(r => r.status === 'occupied').length,
        maintenance: updatedRooms.filter(r => r.status === 'maintenance').length
      };
      
      this.setData({ 
        rooms: updatedRooms,
        roomStats: stats
      });
      this.filterRooms(this.data.searchKeyword);
      
      wx.hideLoading();
      wx.showToast({
        title: '删除成功',
        icon: 'success'
      });
      
      this.onCloseDeleteModal();
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: '删除失败',
        icon: 'error'
      });
      console.error('删除失败:', error);
    }
  },

  // 表单数据变化
  onFormChange(e) {
    const { formData } = e.detail;
    this.setData({ formData });
  },

  // 表单验证
  onFormValidate(e) {
    const { isValid } = e.detail;
    this.setData({ isFormValid: isValid });
  },

  // 确认保存
  async onConfirmSave() {
    if (!this.data.isFormValid) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'error'
      });
      return;
    }

    try {
      wx.showLoading({ title: '保存中...' });
      
      const { formData, isEdit, selectedRoom } = this.data;
      
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 更新本地数据
      const { rooms } = this.data;
      let updatedRooms;
      
      if (isEdit) {
        // 编辑模式
        updatedRooms = rooms.map(room => 
          room._id === selectedRoom._id ? { ...room, ...formData } : room
        );
      } else {
        // 添加模式
        const newRoom = {
          ...formData,
          _id: 'room_' + Date.now(),
          roomId: rooms.length + 1,
          isOccupied: false,
          currentPets: []
        };
        updatedRooms = [...rooms, newRoom];
      }
      
      // 重新计算统计数据
      const stats = {
        total: updatedRooms.length,
        available: updatedRooms.filter(r => r.status === 'available').length,
        occupied: updatedRooms.filter(r => r.status === 'occupied').length,
        maintenance: updatedRooms.filter(r => r.status === 'maintenance').length
      };
      
      this.setData({ 
        rooms: updatedRooms,
        roomStats: stats
      });
      this.filterRooms(this.data.searchKeyword);
      
      wx.hideLoading();
      wx.showToast({
        title: isEdit ? '编辑成功' : '添加成功',
        icon: 'success'
      });
      
      this.onCloseModal();
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: '保存失败',
        icon: 'error'
      });
      console.error('保存失败:', error);
    }
  },

  // 关闭弹窗
  onCloseModal() {
    this.setData({
      showModal: false,
      formData: {},
      isFormValid: false,
      selectedRoom: null
    });
  },

  // 关闭删除确认弹窗
  onCloseDeleteModal() {
    this.setData({
      showDeleteModal: false,
      selectedRoom: null
    });
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止事件冒泡
  }
});
